import wifimgr
import beike
from machine import Pin
import socket
import time
import json

wlan = wifimgr.get_connection()
if wlan is None:
    print("Could not initialize the network connection.")
    while True:
        pass  # you shall not pass :D


# Main Code goes here, wlan is a working network.WLAN(STA_IF) instance.
print("ESP OK")

# 定义引脚2为输出
ledPin = Pin(2, Pin.OUT)
# 定义引脚的初始状态为关闭, 此ESP8266模块中on()为LED熄灭；
ledPin.value(0)
# 再连接贝壳物联
s = socket.socket()
# 设置超时
s.settimeout(10)
beike.connect_bigiot(s)

recvData = b''
t = time.time()
print("The start time is :"+str(t)+"\n")
while True:
    try: # 在超时时间内是否接收到数据
        recvData = s.recv(100)
    except:  # 如果接收不到，维持上线状态
        t = beike.keepOnline(s, t)
        print("Keep online operate, The time now is "+str(t)+"\n")
    if recvData:  # 接收到数据
        msg = json.loads(str(recvData, 'utf-8'))
        print("Received Data is : "+str(msg)+"\n")
        if "C" in msg.keys():  # 接收到offOn的命令，执行操作
            if msg["C"] == "offOn":
                ledPin.value(1)
            elif msg["C"] == "play":
                ledPin.value(0)
            else:
                print("The other C in msg : "+msg+"\n")

            recvData = b''
